HackerRank Highest Value Palindrome
提出
22/33 test cases failed :(
code: python
import math
import os
import random
import re
import sys
from collections import deque
#
# Complete the 'highestValuePalindrome' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING s
# 2. INTEGER n
# 3. INTEGER k limit to change
#
def highestValuePalindrome(s, n, k):
# Write your code here
trim_s = s.replace(' ', '')
diff_idx = deque([])
for i in range((len(trim_s) // 2)):
diff_idx.append(i)
if (len(diff_idx) > k):
return "-1"
list_s = list(trim_s)
for i in diff_idx:
if (k < 0):
break
continue
k -= 1
k -= 1
else:
k -= 2
if (k < 0):
break
else:
return "".join(list_s)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) s = input()
result = highestValuePalindrome(s, n, k)
fptr.write(result + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'highestValuePalindrome' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING s
# 2. INTEGER n
# 3. INTEGER k
#
def highestValuePalindrome(s, n, k):
# Write your code here
s = list(s)
# change the digits to palidrome
l = 0 # left index
r = n-1 # right index
while l <= r:
# just change not swap
else:
k -= 1
l += 1
r -= 1
if k < 0:
return "-1"
# maximize the digits
l = 0
r = n-1
while l <= r:
# center
if l == r and k >= 1:
break
# no changes before
if markl == 0 and markr == 0 and k >= 2: k -= 2
# changed before
if (markl == 1 or markr == 1) and k >= 1: k -= 1
l += 1
r -= 1
return "".join(s)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) s = input()
result = highestValuePalindrome(s, n, k)
fptr.write(result + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=jFjkMADcpsI
提出
22/33 test cases failed :(
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'highestValuePalindrome' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING s
# 2. INTEGER n
# 3. INTEGER k
#
def highestValuePalindrome(s, n, k):
# Write your code here
diff = []
for i in range(n//2):
diff.append((i if change == si else n-1-i, max(si, sn-1-i))) if len(diff) > k:
return "-1"
elif len(diff) == k:
res = list(s)
for i, num in diff:
return "".join(res)
else:
nine = k - len(diff)
res = list(s)
for i, num in diff:
if nine > 0:
nine -= 1
else:
return "".join(res)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) s = input()
result = highestValuePalindrome(s, n, k)
fptr.write(result + '\n')
fptr.close()